#include "game.h"
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<random>
#define N 5000
using namespace std;
mt19937 RAND(random_device{}());
struct reads
{
	int x,y;
};
vector<reads>p[N+1];
int tn,n,length,tong[N+1],rd[N+1];
bool used[N+1];
vector<int>E[N+1];
int get(int x)
{
	if (x>tn) x-=tn;
	if (x<1) x+=tn;
	return x;
}
void add_edge(int x,int y)
{
	E[x].push_back(y),E[y].push_back(x);
	return;
}
void solve(vector<reads>sp,int res)
{
	if (sp.size()==1)
	{
		add_edge(sp[0].x,sp[0].y);
		return;
	}
	vector<reads>A;
	vector<reads>B;
	int mid=sp.size()>>1,d;
	vector<int>tp(n);
	for (int i=1;i<=n;++i) tp[i-1]=rd[i];
	for (int i=0;i<mid;++i) A.push_back(sp[i]),tp[sp[i].x-1]=rd[sp[i].y],tp[sp[i].y-1]=rd[sp[i].x];
	for (int i=mid;i<sp.size();++i) B.push_back(sp[i]);
	d=count(tp);
	if (d) solve(A,d);
	if (res-d) solve(B,res-d);
	return;
}
void dfs(int x)
{
	used[x]=1,tong[++length]=x;
	for (int i=0;i<E[x].size();++i)
		if (!used[E[x][i]])
			dfs(E[x][i]);
	return;
}
vector<int>guess(int sn, int limit)
{
	n=sn;
	vector<int>sp(n);
	vector<int>ans(n);
	for (int i=1;i<=n;++i) sp[i-1]=i;
	while (1)
	{
		shuffle(sp.begin(),sp.end(),RAND);
		if (!count(sp)) break;
	}
	for (int i=1;i<=n;++i) rd[i]=sp[i-1];
	if (!(n&1))
	{
		tn=n-1;
		for (int i=1;i<=n-1;++i)
		{
			p[i].push_back((reads){i,n});
			for (int j=1;j<=(n>>1)-1;++j) p[i].push_back((reads){get(i-j),get(i+j)});
		}
	}
	else
	{
		tn=n;
		for (int i=1;i<=n;++i)
			for (int j=1;j<=(n>>1);++j)
				p[i].push_back((reads){get(i-j),get(i+j)});
	}
	for (int i=1;i<=n;++i)
		if (!p[i].empty())
		{
			for (int j=1;j<=n;++j) sp[j-1]=rd[j];
			for (int j=0;j<p[i].size();++j) sp[p[i][j].x-1]=rd[p[i][j].y],sp[p[i][j].y-1]=rd[p[i][j].x];
			solve(p[i],count(sp));
		}
	for (int i=1;i<=n;++i)
		if (!used[i])
		{
			length=0,dfs(i);
			for (int j=1;j<=n;++j) sp[j-1]=rd[j];
			for (int j=1;j<=length;++j) sp[tong[j]-1]=rd[tong[j%length+1]];
			if (count(sp))
			{
				for (int j=1;j<=length;++j) ans[tong[j]-1]=rd[tong[j%length+1]];
			}
			else
			{
				for (int j=1;j<=length;++j) ans[tong[j%length+1]-1]=rd[tong[j]];
			}
		}
	return ans;
}
